package com.xyauto.theme.vm

import android.app.ActivityManager
import android.app.WallpaperManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.IPackageDataObserver
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import com.blankj.utilcode.util.LogUtils
import com.xyauto.theme.Constant
import com.xyauto.theme.activity.DetailActivity
import com.xyauto.theme.base.SingleLiveEvent
import com.xyauto.theme.base.vm.BaseViewModel
import com.xyauto.theme.bean.IThemeBean
import com.xyauto.theme.bean.JMEThemeBean
import com.xyauto.theme.utils.JieMainYiManager
import com.xyauto.theme.utils.SelectManager

abstract class BaseThemeModel : BaseViewModel() {

    val clearObserver by lazy { SingleLiveEvent<Boolean>() }

    private val mClearDataObserver by lazy {
        object : IPackageDataObserver.Stub() {
            override fun onRemoveCompleted(packageName: String?, succeeded: Boolean) {
                LogUtils.i("onRemoveCompleted: $packageName = $succeeded")
                clearObserver.postValue(succeeded)
            }
        }
    }


    protected fun selectTheme(context: Context, item: IThemeBean): Boolean {
        val isJME = item is JMEThemeBean
        val pakArray = if (isJME) {
            Constant.PAK_JME_LAUNCHER
        } else {
            Constant.PAK_NEW_LAUNCHER
        }.split("&&")
        setDefaultLauncher(context.packageManager, pakArray)
        var isClear = false
        if (item is JMEThemeBean) {
            isClear = clearUserData(context, pakArray[0])
            SelectManager.setSelectTheme(item.index)
            JieMainYiManager.setWallpaper(WallpaperManager.getInstance(context), item.wallpaper)
        } else {
            SelectManager.setSelectTheme("${item.getName()}&&${item.getApkPath()}")
            val intent = Intent(DetailActivity.ACTION_APPLY_THEME)
            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
            intent.setPackage("com.android.launcher")
            intent.putExtra(DetailActivity.EXTRA_KEY_NAME, item.getName())
            intent.putExtra(DetailActivity.EXTRA_KEY_PATH, item.getApkPath())
            context.sendBroadcast(intent)
        }
        return isClear
    }


    protected fun setDefaultLauncher(manager: PackageManager, pakArray: List<String>) {
        val homeFilter = IntentFilter(Intent.ACTION_MAIN)
        homeFilter.addCategory(Intent.CATEGORY_HOME)
        homeFilter.addCategory(Intent.CATEGORY_DEFAULT)
        val homeActivities: MutableList<ResolveInfo> = arrayListOf()
        val allComponents: MutableList<ComponentName> = arrayListOf()
        manager.getHomeActivities(homeActivities)
        for (resolveInfo in homeActivities) {
            allComponents.add(resolveInfo.activityInfo.let {
                ComponentName(it.packageName, it.name)
            })
        }
        manager.replacePreferredActivity(homeFilter, IntentFilter.MATCH_CATEGORY_EMPTY, allComponents.toTypedArray(), ComponentName(pakArray[0], pakArray[1]))
    }


    protected fun clearUserData(context: Context, packageName: String): Boolean {
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val res = am.clearApplicationUserData(packageName, mClearDataObserver)
        LogUtils.i("${if (res) "Success" else "Couldnt"} clear application user data for package:$packageName")
        return res
    }
}